package com.agilestudio.ifinance.entity.account;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import com.agilestudio.ifinance.entity.IdEntity;
import com.agilestudio.modules.utils.reflection.ConvertUtils;

/**
 * 角色.
 * 
 * 注释见{@link User}.
 * 
 * @author Gary
 */
@Entity
@Table(name = "ACCT_ROLE")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role extends IdEntity {

	private String code;
	private String name;
	private String desc;
	private List<Menu> menus = new ArrayList<Menu>();
	private List<Long> menuIds = new ArrayList<Long>();
	
	private List<User> users = new ArrayList<User>();

	public Role() {

	}

	public Role(String code, String name, String desc) {
		this.code = code;
		this.name = name;
		this.desc = desc;
	}

	@Column(nullable = false, unique = true, length = 10)
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	@Column(nullable = false, length = 30)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(name="description",length = 30)
	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	@ManyToMany
	@JoinTable(name = "ACCT_ROLE_MENU", joinColumns = { @JoinColumn(name = "ROLE_ID") }, inverseJoinColumns = { @JoinColumn(name = "MENU_ID") })
	@Fetch(FetchMode.SUBSELECT)
	@OrderBy("code")
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	public List<Menu> getMenus() {
		return menus;
	}

	public void setMenus(List<Menu> menus) {
		this.menus = menus;
	}
	
	@ManyToMany(mappedBy="roles")
	@OrderBy("loginName")
	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	@Transient
	public String getAuthNames() {
		return ConvertUtils.convertElementPropertyToString(menus, "name",
				", ");
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	public void setMenuIds(List<Long> menuIds) {
		this.menuIds = menuIds;
	}
	
	@Transient
	public List<Long> getMenuIds() {
		return menuIds;
	}
}
